# -*- coding: utf-8 -*-
# @Time      : 2025-08-01
# @Author    : 2023090007@ahdy.edu.cn
# @File      : worker
# @Desc  
import gc
import logging
import threading
import os
import signal
import sys
import time
import traceback
from service import Service
from common.loghandler import logger


class Worker(Service):
    """
    执行层
    """

    def __init__(self):
        """

        :param biz
        """
        super().__init__()
        self.running = True  # 初始化服务是启动的
        self.pid = -1 #进程ID
        self.process = None #process
        self.worker_no = -1 #worker_no


    def __call__(self, *args, **kwargs):
        self.pid = os.getpid()
        logger.info("worker process start run ...pid:%s", os.getpid())
        self.signal()
        self.heartbeat()
        self.exec_task()
        # while self.running:  # 0|1
           
        #     try:
        #         # TODO: This should be refactored to call listen in every threads in pool if in thread pool mode.
        #         self.start()
        #     except (KeyboardInterrupt, SystemExit):
        #         logger.warn("Worker:SystemExit, KeyboardInterrupt.")
        #     except Exception as ex:
        #         traceback.print_exc()
        #         logger.error("exception:%s", ex)  # 单次异常不影响子进程
        #     finally:
        #         pass

    def start(self):
        """
        1 设置信号和心跳计时器
        2 分配任务:取消息,放入进程池,等待执行完成
        3 执行任务
        worker_type  处理
        :return:
        """
        logger.info("the worker start ...")
        # self.exec_task()
        # self.heartbeat()

    # 信号处理
    def signal(self):
        """
        :return:
        """
        logger.info("start keep_heartbeat...")
        signal.signal(signal.SIGTERM, self.handle_sigterm)
        signal.signal(signal.SIGINT, self.handle_sigint)
        signal.signal(signal.SIGQUIT, self.handle_sigquit)


    def handle_sigint(self, sig, frame):
        """
        暴力关闭
        :param sig:
        :param frame:
        :return:
        """
        logger.info("worker pid:%s handle_sigint start ...", self.pid)
        os._exit(0)

    def handle_sigterm(self, sig, frame):
        """
        暴力关闭
        :param sig:
        :param frame:
        :return:
        """
        logger.info("worker pid:%s handle_sigterm start ...", self.pid)
        os._exit(0)

    def handle_sigquit(self, sig, frame):
        """
        从容关闭
        :param sig:
        :param frame:
        :return:
        """
        logger.info("worker pid:%s handle_sigquit start ...", self.pid)
        self.running = False


    def heartbeat(self):
        """
        启动心跳线程
        """
        
        t = threading.Thread(target=self.biz)
        t.daemon = True
        t.start()

    # 任务执行
    def exec_task(self):
        """
        查询任务
        1 检查是否分配到当前实例
        2 待提交(提交）重新放入队列
        3 待轮询 轮询, 若成功则执行，否则放入队列
        :return:
        """
        try:
            logger.info("worker pid:%s start exec_task...", self.pid)
            while self.running:

               self.biz.exec(self)
               
               
        except Exception as ex:
            traceback.print_exc()
            logger.exception("worker pid:%s, the worker exec task failed:%s", self.pid, ex)
        finally:
            gc.collect()
        logger.info("worker pid:%s end exec_task.", self.pid)
        os._exit(0)  # 进程退出不执行后面代码 sys.exit(0) 引发一个SystemExit 异常做清理工作